package com.xncoding.freemarker.config;


import com.xncoding.starter.inter.GlobalProperConfig;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;

/**
 * preliminary impl the ProperConfig
 * @author awlwen
 * @since 2017/7/5.
 */
public class ConfigProperties implements GlobalProperConfig {
    private Properties pros;
    private List<String> paths;

    public ConfigProperties(List<String> filePaths) throws Exception {
        paths = filePaths;
        pros = new Properties();
        loadAll();
    }

    private void loadAll() throws Exception {
        InputStreamReader in = null;
        for (int i = 0; i < paths.size(); i++) {
            String file = paths.get(i);
            try {
                in = new InputStreamReader(ConfigProperties.class.getResourceAsStream(file), "UTF-8");
                load(in);
            } catch (IOException e) {
                throw e;
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        throw ex;
                    }
                }
            }
        }
    }

    private void load(InputStreamReader in) throws Exception {
        try {
            pros.load(in);
        } catch (IOException e) {
//            throw new ValidationRuntimeException(ValidationMsg.VALIDATION_FILE_PARSE_ERROR);
            throw e;
        }
    }

    public String getConfig(Object key) {
        return pros.get(key) == null ? "" : pros.get(key).toString();
    }


}
